package com.gykfbxxh.imovie.view.main.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.utils.util.ViewSizeUtils;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.adapter.NewsFragmentPagerAdapter;
import com.gykfbxxh.imovie.base.BaseFragment;
import com.gykfbxxh.imovie.bean.config.ChannelItem;
import com.gykfbxxh.imovie.custom.view.ColumnHorizontalScrollView;
import com.gykfbxxh.imovie.manager.AppChannelManager;
import com.gykfbxxh.imovie.videoplayer.JCVideoPlayer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuxinghai
 * On 2017/8/25
 * 片库fragment
 */

public class HomeFragment extends BaseFragment implements ViewPager.OnPageChangeListener {
    private Activity mActivity;
    private ViewGroup mContentView;//根布局
    /************
     * 页面控件
     *************/
    private ColumnHorizontalScrollView mColumnHorizontalScrollView;
    private LinearLayout mRadioGroup_content;
    private RelativeLayout rl_column;
    private ViewPager mViewPager;
    public ImageView shade_left;
    public ImageView shade_right;
    /************
     * 逻辑数据
     *************/
    private List<ChannelItem> userChannelList = new ArrayList<ChannelItem>();//栏目列表
    private int columnSelectIndex = 0;//当前选中的栏目
    private int mScreenWidth = 0;//屏幕宽度
    private ArrayList<Fragment> fragments = new ArrayList<Fragment>();//新闻页面集合

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(Activity activity) {
        mActivity = activity;
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = (ViewGroup) inflater.inflate(
                    R.layout.fragment_home_page, null);
            initView();
        }


        return mContentView;
    }

    /**
     * 初始化layout控件
     */
    private void initView() {
        mColumnHorizontalScrollView = (ColumnHorizontalScrollView) mContentView
                .findViewById(R.id.mColumnHorizontalScrollView);
        mRadioGroup_content = (LinearLayout) mContentView
                .findViewById(R.id.mRadioGroup_content);
        rl_column = (RelativeLayout) mContentView.findViewById(R.id.rl_column);
        mViewPager = (ViewPager) mContentView.findViewById(R.id.mViewPager);
        shade_left = (ImageView) mContentView.findViewById(R.id.shade_left);
        shade_right = (ImageView) mContentView.findViewById(R.id.shade_right);
        setChangelView();
    }


    /**
     * 初始化栏目项时候调用
     */
    public void setChangelView() {
        initColumnData();
        initTabColumn();
        initFragment();
    }

    /**
     * 获取Column栏目 数据
     */
    private void initColumnData() {
        userChannelList = AppChannelManager.getInstance().getUserChannel();
    }

    /**
     * 初始化Column栏目项
     */
    private void initTabColumn() {
        mScreenWidth = ViewSizeUtils.getWidthPixels();
        mRadioGroup_content.removeAllViews();
        int count = userChannelList.size();
        mColumnHorizontalScrollView.setParam(mActivity, mScreenWidth, count,
                mRadioGroup_content, shade_left, shade_right,
                rl_column);

        int itemWidth = mColumnHorizontalScrollView.getItemWidth();
        LayoutInflater inflayouter = mActivity.getLayoutInflater();
        for (int i = 0; i < count; i++) {
            final String chanelname = userChannelList.get(i).getName();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    itemWidth,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            // params.leftMargin = DataTools.dip2px(mActivity, 8);
            // params.rightMargin = params.leftMargin;
            TextView columnTextView = (TextView) inflayouter.inflate(R.layout.layout_scroll_text, null);
//            TextView columnTextView = (TextView) view
//                    .findViewById(R.id.text_channel);// new
            // TextView(mActivity);
            columnTextView.setTextAppearance(mActivity,
                    R.style.top_category_scroll_view_item_text);
            // columnTextView.setPadding(5, 5, AppSizeUtils.dp2px(mActivity,5),
            // AppSizeUtils.dp2px(mActivity,5));
            columnTextView.setPadding(5, 5, 5, 5);
            columnTextView.setText(chanelname);
            if (columnSelectIndex == i) {
                columnTextView.setSelected(true);
            }
            columnTextView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
                        View localView = mRadioGroup_content.getChildAt(i);
                        if (localView != v) {
                            localView.setSelected(false);
                        } else {
                            //释放播放器资源
                            JCVideoPlayer.releaseAllVideos();
                            localView.setSelected(true);
                            mViewPager.setCurrentItem(i + 1);
                            if(v != null && v.getTag() != null){
                                flushCurrentPage();
                            }else if(v != null){
                                v.setTag("true");
                            }

                        }
                    }
                }
            });
            mRadioGroup_content.addView(columnTextView, i, params);
        }
    }

    /**
     * 初始化Fragment新闻页面
     */
    private void initFragment() {
        fragments.clear();// 清空
        int count = userChannelList.size();
        for (int i = 0; i < count; i++) {
            Bundle data = new Bundle();
            data.putString("id", userChannelList.get(i).getId());
            data.putString("name", userChannelList.get(i).getName());
            data.putString("type", userChannelList.get(i).getTypeid());
            if (i == 0) {
                data.putString("focus_news", "focus");
            }
            FilmsFragment filmsFragment;
            filmsFragment = new FilmsFragment();
            filmsFragment.setArguments(data);
            fragments.add(filmsFragment);
        }
        // 在第一个位置加入最后一个数据
        Fragment filmsFragment = new Fragment();
        fragments.add(0, filmsFragment);
        // 在最后一个位置加入第一个数据
        filmsFragment = new Fragment();
        fragments.add(filmsFragment);
        // 开始适配
        NewsFragmentPagerAdapter mAdapetr = new NewsFragmentPagerAdapter(
                getChildFragmentManager(), fragments);
        // mViewPager.setOffscreenPageLimit(0);
        mViewPager.setAdapter(mAdapetr);
        mViewPager.setOnPageChangeListener(this);
        mViewPager.setCurrentItem(1);
    }


    /* 刷新当前页面数据 */
    public void flushCurrentPage() {
        if (fragments == null || mViewPager == null) {
            return;
        }
        FilmsFragment currentFragment = (FilmsFragment) fragments.get(mViewPager.getCurrentItem());
        if (currentFragment != null) {
            currentFragment.flushData();
        }

    }


    /**
     * 选择的Column里面的Tab
     */
    private void selectTab(int tab_postion) {
        columnSelectIndex = tab_postion;

        if (userChannelList.size() > 5) {
            for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
                View checkView = mRadioGroup_content.getChildAt(tab_postion);
                int k = checkView.getMeasuredWidth();
                int l = checkView.getLeft();
                int i2 = l + k / 2 - mScreenWidth / 2;
                // rg_nav_content.getParent()).smoothScrollTo(i2, 0);
                mColumnHorizontalScrollView.smoothScrollTo(i2, 0);
                // mColumnHorizontalScrollView.smoothScrollTo((position - 2) *
                // mItemWidth , 0);
            }
        }

        // 判断是否选中
        for (int j = 0; j < mRadioGroup_content.getChildCount(); j++) {
            View checkView = mRadioGroup_content.getChildAt(j);
            boolean ischeck;
            if (j == tab_postion) {
                ischeck = true;
            } else {
                ischeck = false;
            }
            checkView.setSelected(ischeck);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position < 1) {
            position = fragments.size() - 3;
        } else if (position > fragments.size() - 2) {
            position = 0;
        } else {
            position--;
        }
        //释放播放器资源
        JCVideoPlayer.releaseAllVideos();
        selectTab(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == 0) {
            if (mViewPager.getCurrentItem() < 1) {
                mViewPager.setCurrentItem(fragments.size() - 2, false);
            } else if (mViewPager.getCurrentItem() > fragments.size() - 2) {
                mViewPager.setCurrentItem(1, false);
            }
        }
    }
}
